package sy.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/fileController")
public class FileController {

	@RequestMapping("/upload")
	@ResponseBody
	public String upload() {

		return "失败";
	}

	@RequestMapping("pic_add.action")
	@ResponseBody
	public String  uploadHeaderPicAdd(String inputId, MultipartHttpServletRequest request) {
		String date=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			MultipartFile realPicFile = request.getFile(inputId);
			InputStream in = realPicFile.getInputStream();
			String path = request.getSession().getServletContext().getRealPath("/");
			path += "../ROOT/uploadfiles";
			String fileName =date + "." + FilenameUtils.getExtension(realPicFile.getOriginalFilename());
			File f = new File(path + "/" + fileName);
			FileUtils.copyInputStreamToFile(in, f);
			return fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	@RequestMapping("pic_edit.action")
	@ResponseBody
	public String  uploadHeaderPicEdit(String inputId, MultipartHttpServletRequest request,String id) {
		try {
			MultipartFile realPicFile = request.getFile(inputId);
			InputStream in = realPicFile.getInputStream();
			String path = request.getSession().getServletContext().getRealPath("/");
			path += "../ROOT/uploadfiles";
			String fileName =id + "." + FilenameUtils.getExtension(realPicFile.getOriginalFilename());
			File f = new File(path + "/" + fileName);
			FileUtils.copyInputStreamToFile(in, f);
			return fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
